import { SignalMessage } from "../type";
type MessageHandler = (msg:SignalMessage) => void;

export class SignalClient{
    private ws : WebSocket | null = null;
    private url: string;
    private messageHandler: MessageHandler[] = [];

    constructor(url: string) {
        this.url = url;
    }

    public async connect(): Promise<WebSocket> {
        return new Promise((resolve, reject) => {
            this.ws = new WebSocket(this.url);
            this.ws.onopen = () => {
                console.log("Connected to signaling server");
                resolve(this.ws!);
            }
            this.ws.onmessage = (event) => {
                try{
                    console.log("Received message from signaling server:", event.data);
                    const message: SignalMessage = JSON.parse(event.data);
                    this.notifyHandlers(message);
                }catch(e){
                    console.log("Error:", e);
                }
            }
            this.ws.onerror = (error) => {
                console.log("WebSocket error:", error);
                reject(error);
            }
            this.ws.onclose = () => {
                console.log('Disconnected from signaling server');
                this.ws = null;
            }
        });
    }

    public send(message: SignalMessage) { 
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN){
            console.log("WebSocket is not open");
            return;
        }
        this.ws?.send(JSON.stringify(message));
    }

    public disconnect() { 
        if (this.ws) {
            this.ws.close();
        }
    }

    // 观察者模式，注册消息处理函数
    public onMessage(handler: MessageHandler) { 
        this.messageHandler.push(handler);
    }

    // 当实际收到消息时调用处理方法
    private notifyHandlers(message: SignalMessage) { 
        this.messageHandler.forEach(handler => handler(message));
    }
}